const express = require('express');
const router = express.Router();
const { Chapter, Course } = require('../../models')
const { Op } = require('sequelize')
const { success, failure } = require('../../utils/responses');
const{NotFoundError}=require('../../utils/errors')


//查询章节列表
router.get('/', async function (req, res) {
    try {
        const query = req.query
        // 当前页数，如果不传值默认第一页
        const currentPage = Math.abs(Number(query.currentPage)) || 1
        // 每页显示的数量，如果不传值默认10
        const pageSize = Math.abs(Number(query.pageSize)) || 10
        //计算offset
        const offset = (currentPage - 1) * pageSize

        if (!query.courseId) {
            throw new Error('获取章节失败，课程ID不能为空')
        }
        const condition = {
            ...getCondition(),
            order: [['rank', 'ASC'], ['id', 'ASC']],
            limit: pageSize,
            offset: offset
        }

        condition.where = {
            courseId: {
                [Op.eq]: query.courseId
            }
        }
        if (query.title) {
            condition.where = {
                title: {
                    [Op.like]: `%${query.title}%`
                }
            }
        }

        const { count, rows } = await Chapter.findAndCountAll(condition)
        success(res, '章节查询成功', {
            chapters: rows,
            pagination: {
                total: count,
                currentPage,
                pageSize
            }
        })
    } catch (error) {
        failure(res, error)
    }

})
//查询章节详情
router.get('/:id', async function (req, res) {
    try {
        const chapter = await getChapter(req)
        success(res, '查询章节成功', { chapter })

    } catch (error) {
        failure(res, error)
    }

})

//创建章节
router.post('/', async function (req, res) {
    try {
        //创建白名单过滤
        const body = filterBody(req)
        const chapter = await Chapter.create(body);
        //200和201都表示成功,201表示创建新的资源
        success(res, '创建章节成功', { chapter }, 201)
    } catch (error) {
        failure(res, error)
    }
})

//删除章节
router.delete('/:id', async function (req, res) {
    try {
        const chapter = await getChapter(req)
        await chapter.destroy()
        success(res, '删除章节成功')
    } catch (error) {
        failure(res, error)
    }
})

//更新章节
router.put('/:id', async function (req, res) {
    try {
        const chapter = await getChapter(req)

        //创建白名单过滤
        const body = filterBody(req)

        //更新章节
        await chapter.update(body)
        success(res, '更新章节成功', { chapter })

    } catch (error) {
        failure(res, error)
    }
})

//关联查询
function getCondition() {
    return {
        attributes: { exclude: ['CourseId'] },
        include: [
            {
                model: Course,
                as: 'course',
                attributes: ['id', "name"]
            },
        ]
    }
}

//查询当前章节：公共方法
async function getChapter(req) {
    //获取章节ID
    const { id } = req.params
    const condition = getCondition()
    //查询当前章节ID
    const chapter = await Chapter.findByPk(id, condition)

    //如果章节不存在，抛出错误异常
    if (!chapter) {
        throw new NotFoundError(`ID:${id}章节不存在`)
    }
    return chapter
}

// 白名单过滤：公共方法
function filterBody(req) {
    return {
        courseId: req.body.courseId,
        title: req.body.title,
        content: req.body.content,
        video: req.body.video,
        rank: req.body.rank
    }
}
module.exports = router;